<template>
  <div>
    <!-- 工具栏 -->
    <div class="toolbar" style="margin-bottom: 16px;">
      <el-button type="primary" @click="dialogVisible = true" style="margin-right: 8px;">新增</el-button>
      <el-button 
        type="danger" 
        :disabled="multipleSelection.length === 0"
        @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <!-- 新增排班计划弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加排班计划" width="600px" @close="resetForm">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="计划编号" prop="shiftCode">
          <el-input v-model="form.shiftCode" :disabled="autoGenerate" style="width: 220px; margin-right: 10px;" />
          <el-switch v-model="autoGenerate" active-text="自动生成" style="margin-left: 10px;" />
        </el-form-item>
        <el-form-item label="计划名称" prop="shiftName">
          <el-input v-model="form.shiftName" />
        </el-form-item>
        <el-form-item label="开始日期" prop="beginTime">
          <el-date-picker v-model="form.beginTime" type="date" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endTime">
          <el-date-picker v-model="form.endTime" type="date" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="班组类型" prop="teamTypeId">
          <el-select v-model="form.teamTypeId" placeholder="请选择班组类型" style="width: 100%;">
            <el-option v-for="item in teamTypes" :key="item.id" :label="item.teamTypeName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="轮班方式">
          <el-radio-group v-model="form.shiftmodel">
            <el-radio :label="1">白班</el-radio>
            <el-radio :label="2">两班倒</el-radio>
            <el-radio :label="3">三班倒</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="倒班方式" v-if="form.shiftmodel !== 1">
          <el-select v-model="form.pourmodel" style="width: 100%;">
            <el-option label="按天" :value="1" />
            <el-option label="按周" :value="2" />
            <el-option label="按月" :value="3" />
            <el-option label="按季度" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" />
        </el-form-item>
        <el-form-item label="单据状态" prop="documentstatus">
          <el-radio-group v-model="form.documentstatus">
            <el-radio :label="1">已确认</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchAdd">确定</el-button>
      </template>
    </el-dialog>

    <!-- 表格 -->
    <el-table 
      :data="tableData"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="shiftCode" label="计划编号" align="center" />
      <el-table-column prop="shiftName" label="计划名称" align="center" />
      <el-table-column prop="teamTypeName" label="班组类型" align="center" />
      <el-table-column label="开始日期" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.beginTime) }}
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="轮班方式" align="center">
        <template #default="scope">
          {{ formatShiftModel(scope.row.shiftmodel) }}
        </template>
      </el-table-column>
      <el-table-column label="倒班方式" align="center">
        <template #default="scope">
          {{ formatPourModel(scope.row.pourmodel) }}
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.documentstatus === 1 ? 'success' : 'info'">
            {{ formatDocumentStatus(scope.row.documentstatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120" align="center">
        <template #default="scope">
          <template v-if="scope.row.documentstatus !== 1">
            <el-button link type="primary" size="small">修改</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import http from '@/api/http';
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const tableData = ref([])
const multipleSelection = ref([]) // 存储选中的行数据
const dialogVisible = ref(false)
const formRef = ref()
const autoGenerate = ref(false)
const form = reactive({
  shiftCode: '',
  shiftName: '',
  beginTime: '',
  endTime: '',
  teamTypeId: '',
  shiftmodel: 1, // 1:白班 2:两班倒 3:三班倒
  pourmodel: 3,  // 1:按天 2:按周 3:按月 4:按季度
  remark: '',
  documentstatus: 0 // 0:草稿 1:已确认
})
const rules = {
  shiftCode: [{ required: true, message: '请输入计划编号', trigger: 'blur' }],
  shiftName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  beginTime: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endTime: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && form.beginTime && dayjs(value).isBefore(dayjs(form.beginTime))) {
          callback(new Error('结束日期不能小于开始日期'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  teamTypeId: [{ required: true, message: '请选择班组类型', trigger: 'change' }],
  documentstatus: [{ required: true, message: '请选择单据状态', trigger: 'change' }]
}
const teamTypes = ref([])

// 自动生成计划编号
watch(autoGenerate, (val) => {
  if (val) {
    form.shiftCode = 'PLAN' + dayjs().format('YYYYMMDDHHmmss')
  } else {
    form.shiftCode = ''
  }
})

// 轮班方式切换时，倒班方式联动
watch(() => form.shiftmodel, (val) => {
  if (val === 1) {
    form.pourmodel = 3 // 白班默认按月
  }
})

function resetForm() {
  form.shiftCode = ''
  form.shiftName = ''
  form.beginTime = ''
  form.endTime = ''
  form.teamTypeId = ''
  form.shiftmodel = 1
  form.pourmodel = 3
  form.remark = ''
  form.documentstatus = 0
  autoGenerate.value = false
  formRef.value && formRef.value.clearValidate()
}

function getDaysCount(start, end) {
  return dayjs(end).diff(dayjs(start), 'day') + 1
}

function getBatchData() {
  const days = getDaysCount(form.beginTime, form.endTime)
  let count = days
  if (form.shiftmodel === 2) count = days * 2
  if (form.shiftmodel === 3) count = days * 3
  const selectedTeam = teamTypes.value.find(item => item.id == form.teamTypeId)
  const data = []
  for (let i = 0; i < count; i++) {
    data.push({
      shiftCode: form.shiftCode,
      shiftName: form.shiftName,
      beginTime: form.beginTime,
      endTime: form.endTime,
      teamTypeId: Number(form.teamTypeId),
      teamType: selectedTeam ? selectedTeam.teamType : '',
      shiftmodel: form.shiftmodel,
      pourmodel: form.shiftmodel === 1 ? 3 : form.pourmodel,
      remark: form.remark,
      documentstatus: form.documentstatus
    })
  }
  return data
}

function handleBatchAdd() {
  formRef.value.validate(valid => {
    if (!valid) return
    const data = getBatchData()
    http.post('/api/Shiftplanning/BatchAddShiftplannings', data).then(res => {
      if (res.status) {
        ElMessage.success('批量添加成功')
        dialogVisible.value = false
        getShiftPlanningList()
      } else {
        ElMessage.error(res.message || '批量添加失败')
      }
    })
  })
}

// 选择项发生变化时的处理
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  ElMessageBox.confirm(`确认要删除选中的 ${multipleSelection.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const ids = multipleSelection.value.map(item => item.id)
        const queryString = ids.map(id => `ids=${id}`).join('&')
        const response = await http.get(`/api/Shiftplanning/BatchDeleteShiftplannings?${queryString}`)
        if (response.status === true || response.status === 1) {
          ElMessage.success('删除成功')
          multipleSelection.value = []
          getShiftPlanningList()
        } else {
          throw new Error(response.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '删除失败，请稍后重试')
      }
    })
    .catch(() => {
      // 用户取消删除操作，不做任何处理
    })
}

// 单条删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该数据吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const ids = [row.id]
    http.get(`/api/Shiftplanning/BatchDeleteShiftplannings?ids=${ids.join(',')}`).then(res => {
      if (res.status) {
        ElMessage.success('删除成功')
        getShiftPlanningList() // 刷新列表
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    })
  }).catch(() => {
    // 取消删除
  })
}

// 格式化日期，只显示年月日
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 格式化轮班方式
const formatShiftModel = (value) => {
  const shiftModelMap = {
    1: '白班',
    2: '两班倒',
    3: '三班倒'
  }
  return shiftModelMap[value] || value
}

// 格式化倒班方式
const formatPourModel = (value) => {
  const pourModelMap = {
    1: '按天',
    2: '按周',
    3: '按月',
    4: '按季度'
  }
  return pourModelMap[value] || value
}

// 格式化单据状态
const formatDocumentStatus = (value) => {
  const statusMap = {
    0: '草稿',
    1: '已确认'
  }
  return statusMap[value] || value
}

const getShiftPlanningList = () => {
  http.get('/api/Shiftplanning/GetShiftplanningList').then(res => {
    // 兼容后端主键不是id的情况，统一成id字段
    tableData.value = (res.data || []).map(item => ({
      ...item,
      id: item.id ?? item.shiftId ?? item.ID // 这里根据实际后端主键名调整
    }))
  })
}

onMounted(() => {
  getShiftPlanningList()
  http.get('/api/TeamTypeModel/GetTeamType').then(res => {
    teamTypes.value = res.data || []
  })
})
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>